package com.mengchengnet.chaperonage.util;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.component.imageloader.ImageLoaderHelper;
import com.mengchengnet.chaperonage.view.CustomizedAlertDialog;
import com.mengchengnet.chaperonage.view.CustomizedProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 16-1-4.
 */
public class ViewUtil {
    private static final String TAG = "ViewUtil";
    private static LayoutInflater inflater;
    private static boolean type = true;             //用于判断跳转安装页面是否关闭程序

    /**
     * 关闭键盘
     */
    public static synchronized void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) BaseActivity.currentActivity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (ValueUtil.isNotEmpty(imm)) {
            View focusView = BaseActivity.currentActivity.getCurrentFocus();
            if (ValueUtil.isNotEmpty(focusView)) {
                imm.hideSoftInputFromWindow(focusView.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    public static void showProgressDialog(String msg, boolean cancelable, DialogInterface.OnCancelListener cancelListener) {
        hideProgressDialog();
        CustomizedProgressDialog.showDialog(BaseActivity.currentActivity, msg, cancelable, cancelListener);
    }

    public static CustomizedProgressDialog showProgressDialog(String msg) {
        hideProgressDialog();
        CustomizedProgressDialog dialog = CustomizedProgressDialog.showDialog(BaseActivity.currentActivity, msg, true, null);
        return dialog;
    }

    public static CustomizedProgressDialog showProgressDialog(int resID) {
        hideProgressDialog();
        CustomizedProgressDialog dialog = CustomizedProgressDialog.showDialog(BaseActivity.currentActivity, getStringByResID(resID), true, null);
        return dialog;
    }

    public static void showNoncancelableProgressDialog(String msg) {
        hideProgressDialog();
        CustomizedProgressDialog.showDialog(BaseActivity.currentActivity, msg, false, null);
    }

    public static void hideProgressDialog() {
        CustomizedProgressDialog.hideDialog();
    }

    public static CustomizedAlertDialog.Builder alertForNfc(String msg) {

        CustomizedAlertDialog.Builder customBuilder = new CustomizedAlertDialog.Builder(BaseActivity.currentActivity);
        customBuilder.setTitle("提示");
        customBuilder.setMessage(msg);
        customBuilder.setCancelable(false);
        customBuilder.showDialog();
        return customBuilder;
    }

    public static void alert(String msg) {

        CustomizedAlertDialog.Builder customBuilder = new CustomizedAlertDialog.Builder(BaseActivity.currentActivity);
        customBuilder.setTitle("提示");
        customBuilder.setMessage(msg);
        customBuilder.setNeutralButton(R.string.alert_dialog_confirm, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        customBuilder.showDialog();
    }

    public static void alertAndFinish(String msg) {

        CustomizedAlertDialog.Builder customBuilder = new CustomizedAlertDialog.Builder(BaseActivity.currentActivity);
        customBuilder.setTitle("提示");
        customBuilder.setMessage(msg);
        customBuilder.setNeutralButton(R.string.alert_dialog_confirm, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                BaseActivity.currentActivity.finish();
            }
        });
        customBuilder.showDialog();
    }

    public static void alert(String msg, OnClickListener listener) {

        CustomizedAlertDialog.Builder customBuilder = new CustomizedAlertDialog.Builder(BaseActivity.currentActivity);
        customBuilder.setTitle("提示");
        customBuilder.setMessage(msg);
        customBuilder.setPositiveButton(R.string.alert_dialog_confirm, listener);
        customBuilder.setNegativeButton(R.string.alert_dialog_cancel, new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        customBuilder.showDialog();
    }

    public static void alert(String msg, OnClickListener positiveListener, OnClickListener negativeListener) {

        CustomizedAlertDialog.Builder customBuilder = new CustomizedAlertDialog.Builder(BaseActivity.currentActivity);
        customBuilder.setTitle("提示");
        customBuilder.setMessage(msg);
        customBuilder.setPositiveButton(R.string.alert_dialog_confirm, positiveListener);
        customBuilder.setNegativeButton(R.string.alert_dialog_cancel, negativeListener);

        customBuilder.showDialog();
    }

    public static void alert(String msg, String positiveButtonText, OnClickListener positiveListener,
                             String negativeButtonText, OnClickListener negativeListener) {

        CustomizedAlertDialog.Builder customBuilder = new CustomizedAlertDialog.Builder(BaseActivity.currentActivity);
        customBuilder.setTitle("提示");
        customBuilder.setMessage(msg);
        customBuilder.setPositiveButton(positiveButtonText, positiveListener);
        customBuilder.setNegativeButton(negativeButtonText, negativeListener);
        customBuilder.showDialog();
    }

    public static void showToast(String msg) {
        Toast.makeText(BaseActivity.currentActivity, msg, Toast.LENGTH_LONG).show();
    }

    public static void showToast(int msgId) {
        Toast.makeText(BaseActivity.currentActivity, msgId, Toast.LENGTH_LONG).show();
    }

    /**
     * 创造进度条并显示
     */
    /**
     * 获取string.xml上的内容
     */
    public static String getStringByResID(int resID) {
        String msg = BaseActivity.currentActivity.getString(resID);
        return msg;
    }

    /**
     * 创建视图(top)
     */
    private static LayoutInflater getInflater() {
        if (null == inflater) {
            inflater = LayoutInflater.from(BaseActivity.currentActivity);
        }
        return inflater;
    }

    public static View buildView(int layout) {
        return getInflater().inflate(layout, null);
    }

    /**
     * 动态设置 listview在scrollview中 子布局的高度
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    /**
     * 根据imageName判断是显示图片还是现实默认的图片
     */
    public static void showImageView(Context context, ImageView imageView, String imageUrl) {
        ImageLoader.getInstance().displayImage(imageUrl, imageView, new ImageLoaderHelper(context).getOptions());
    }


    /**
     * 下载apk
     */
    public static void downloadApk(final Context context, final String urlString, final CustomizedProgressDialog progressDialog, final Activity activity) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    String mySavePath = Environment.getExternalStorageDirectory() + "/" + "download";
                    URL url = null;
                    try {
                        url = new URL(urlString);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                    try {
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.connect();
                        InputStream is = connection.getInputStream();
                        File file = new File(mySavePath);
                        if (!file.exists()) {
                            file.mkdir()
                            ;
                        }
                        File apkFile = new File(mySavePath, "hbykt.apk");
                        FileOutputStream fos = new FileOutputStream(apkFile);
                        int numread = 0;
                        byte buf[] = new byte[1024 * 4];
                        while ((numread = is.read(buf)) != -1) {
                            fos.write(buf, 0, numread);
                            fos.flush();
                        }
                        is.close();
                        fos.close();
                        installAPK(apkFile, context, activity);
                        progressDialog.dismiss();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

    }

    /**
     * 安装apk
     */
    public static void installAPK(File file, Context context, Activity activity) {
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        if (type) {
            activity.finish();
        }
    }
}
